<?php
/**
 * Tablesorter extension for Yii.
 *
 * jQuery tablesorter extension for Yii, for turning a standard grid view into a sortable table without page refreshes.
 * Its a wrapper of  https://github.com/Mottie/tablesorter
 *
 * @author Nachi <innovativenachi@gmail.com>
 * @link https://github.com/Mottie/tablesorter
 * @link https://github.com/innovativenachi/tablesorter
 * @version 0.1
 *
 */
class Sorter extends CWidget
{
	//Parameters passed
	private $_options = array(
        'data'    => null,
        'columns'   => null,
        'filters'   => null,
		'page'	=>null,
		'view'=>null,
		'fullAction'=>null,
		'isViewQuotation'=>false,
		'model'=>0,
    );
    
    public function init()
	{
		//Table sorter was intialized
	}
	
	//Magic function for get parameters
	public function __get($name) {
        if(array_key_exists($name, $this->_options)) {
            return $this->_options[$name];
        }
        return parent::__get($name);
    }
	
	//Magic function for setting parameters
    public function __set($name, $value) {
        if(array_key_exists($name, $this->_options)) {
            return $this->_options[$name] = $value;
        }
        return parent::__set($name, $value);
    }
	
	//Register CSS and Jquery
	public function registerClientScript()
	{
		$bu = Yii::app()->assetManager->publish(dirname(__FILE__) . '/assets/');
        $cs = Yii::app()->clientScript;
        //Intialize CSS
        $cs->registerCssFile($bu . '/css/tablesorter.css');
		$cs->registerCssFile($bu . '/css/tablesorter.pager.css');
		$cs->registerCssFile($bu . '/css/bootstrap.css');
		//Intialize Jquery
		$cs->registerScriptFile($bu . '/js/jquery-1.10.2.js');
		$cs->registerScriptFile($bu . '/js/tablesorter.js');
		$cs->registerScriptFile($bu . '/js/tablesorter.pager.js');
		$cs->registerScriptFile($bu . '/js/tablesorter.widgets.js');
		$cs->registerScriptFile($bu . '/js/tablesorter.widgets-filter-formatter.js');
		$cs->registerScriptFile($bu . '/js/scripts.js');
	}
	
	public function genTable()
	{
		$page=$this->page;
		$view=$this->view;
		$datas=$this->data;
		$model=$this->model;
		$fullAction=$this->fullAction;
		$view_url='';
		if(!empty($datas)) { //for not empty values
		$object=$datas[0];
		$class=get_class($object);
		}
		$count=count($datas);
		if(!$this->isViewQuotation)
			echo "Totaly ".$count." results have been found";
		
		//Table start
		echo "<table class='tablesorter-bootstrap'>\n";
		//Table head start
		echo "<thead>\n";
		echo "<tr>\n";
		$filters=$this->filters;
		$i=0;
		$arrayTemp = array(new Customer, new Product, new QuotationOrderHeader, new QuotationOrderDetail);
		$zx= $arrayTemp[$model];
		foreach($this->columns as $column)
		{
			$find = explode(".", $column);
			
			if(count($find)>1) {
			echo "<th class='".$filters[$i]."'>".$zx->getAttributeLabel($find[1])."</th>";	
			}
			else
			echo "<th class='".$filters[$i]."'>".$zx->getAttributeLabel($column)."</th>";
			
			$i++;
		}
		/*if($page=='QuotationOrderDetail'){
			echo "<th class='filter-false'>Total</th>";
		}*/
		
		
		//tampilkan status delete untuk admin
		/*if(isset(Yii::app()->session['adminUser']) && $page=='controller'){
			echo "<th class='filter-false'>Status</th>";		
		}*/

		echo "<th class='filter-false'>Actions</th>";
		echo "</tr>\n";
		echo "</thead>\n";
		//Table head end
		
		//Table body start
		echo "<tbody>\n";
		
		foreach($datas as $data)
		{
			echo "<tr>\n";
			foreach($this->columns as $column)
			{
				$find = explode(".", $column);
				if(count($find)>1) {
					echo "<td>".$data->$find[0]->$find[1]."</td>";
				}
				else {	
					if($page=='controller' && $column==$data->tableSchema->primaryKey){//<i class='icon-exclamation-sign'></i>
					$date1 = strtotime(date("Y-m-d"));
						if($view=='Invoice'){
							$title=date("Y-m-d",strtotime("$data->date_invoice +$data->due_date days"));
							$date2 = strtotime($data->date_invoice);
							$subtDate=($date1-$date2)/86400;
							if($data->due_date/$subtDate<=1){//(float)()
								echo "<td title='$title'>".$data->$column."<span class='label label-important' style='float:right'>!</span></td>";
							}else if($data->due_date/$subtDate==2){
								echo "<td title='$title'>".$data->$column."<span class='label label-warning' style='float:right'>!</span></td>";
							}else{
								echo "<td>".$data->$column."</td>";
							}
						}
						else if($view=='PurchaseOrderHeader'){
							echo "<td>".$data->$column."</td>";
						}
						else if($view=='QuotationOrderHeader'){
							echo "<td>".$data->$column."</td>";
						}
					}else{
						echo "<td>".$data->$column."</td>";
					}
				}
			}

			//tampilkan status delete untuk admin
			/*if(isset(Yii::app()->session['adminUser']) && $page=='controller'){
				echo "<td>".$data->status_delete."</td>";
			}*/

			//View, Edit and Delete Urls
			if($view=='QuotationOrderHeader' || $view=='PurchaseOrderHeader'){
				$view_url=Yii::app()->controller->createAbsoluteUrl($class.'/view'.$view,array('id'=>$data->primaryKey));
				//$tempGenerate=$data->generate;
			}
			else if($page=='addItem'){
				//$tempProduct = array($data->product_pn,$data->unit_buy);
				$tempProduct = $data->product_pn;
				$tempSell=$data->unit_sell;
				$tempData=array($tempProduct,$tempSell);
			}
			else{
				$view_url=Yii::app()->controller->createAbsoluteUrl($class.'/view',array('id'=>$data->primaryKey));
			}
			
			$edit_url=Yii::app()->controller->createAbsoluteUrl($class.'/update',array('id'=>$data->primaryKey));
			$delete_url=Yii::app()->controller->createAbsoluteUrl($class.'/delete',array('id'=>$data->primaryKey));
			$view_pdf=Yii::app()->controller->createAbsoluteUrl($class.'/viewPDF',array('id'=>$data->primaryKey));
			
			/*if($view=='QuotationOrderDetail'||$view=='PurchaseOrderDetail'){
				$view_url=Yii::app()->controller->createAbsoluteUrl($view.'/view',array('p_pn'=>$data->product_pn,'quo_no'=>$data->quotation_no,'uom'=>$data->uom));
				$edit_url=Yii::app()->controller->createAbsoluteUrl($view.'/update',array('p_pn'=>$data->product_pn,'quo_no'=>$data->quotation_no,'uom'=>$data->uom));
				$delete_url=Yii::app()->controller->createAbsoluteUrl($view.'/delete',array('p_pn'=>$data->product_pn,'quo_no'=>$data->quotation_no,'uom'=>$data->uom));
			}*/
			/*if($view=='PurchaseOrderDetail'){
				$view_url=Yii::app()->controller->createAbsoluteUrl($class.'/view',array('p_pn'=>$data->product_pn,'quo_no'=>$data->quotation_no,'uom'=>$data->uom));
				$edit_url=Yii::app()->controller->createAbsoluteUrl($class.'/update',array('p_pn'=>$data->product_pn,'quo_no'=>$data->quotation_no,'uom'=>$data->uom));
				$delete_url=Yii::app()->controller->createAbsoluteUrl($class.'/delete',array('p_pn'=>$data->product_pn,'quo_no'=>$data->quotation_no,'uom'=>$data->uom));
			}*/
			
			
			//View, Edit, Delete Icons (bootstrap)
			echo "<td>";
			if($page!='addItem'){
				echo "   <a class='btn btn-small' href='".$view_url."'><i class='icon-search'></i></a>";
				if(isset(Yii::app()->session['adminUser']) && $page!='controller' && $page!=null
				 /*|| $view=='QuotationOrderDetail' && $fullAction */|| $fullAction){
					echo "&nbsp; <a class='btn btn-small' href='".$edit_url."'><i class='icon-edit'></i></a>
						  &nbsp; <a class='btn btn-small' href='".$delete_url."'><i class='icon-trash'></i></a>";
				}else if(isset(Yii::app()->session['adminUser']) && $page=='controller'){
					if($data->generate==1)
					echo "&nbsp; <a class='btn btn-small' target='_blank' href='".$view_pdf."'><i class='icon-file'></i></a>";
				}
			}else{
				?>
				<a  class='btn btn-small' 
					onClick="$('#product_pn').val('<?php echo $tempData[0]; ?>'); 
							 $('#unit_sell').val('<?php echo $tempData[1]; ?>');
							 $('#unit_sell_hidden').val(Number($('#unit_sell').val().replace(/[^0-9\.-]+/g,'')));
							 
							 $('#total').val('<?php echo $tempData[1]; ?>');
							 $('#qty').val('1');
							 $('#mydialog2').dialog('close');"
				>
							 
					<i class='icon-plus-sign'></i>
				</a>
				<?php
			}
			echo "</td>";
			echo "</tr>\n";
		}
		echo "</tbody>\n";
		//Table body end
		
		//Table footer start
		if(!$this->isViewQuotation){
		echo "<tfoot>\n";
		echo '<tr>
				<th colspan="7" class="pager form-horizontal">
					<button type="button" class="btn first"><i class="icon-step-backward"></i></button>
					<button type="button" class="btn prev"><i class="icon-arrow-left"></i></button>
					<span class="pagedisplay"></span> <!-- this can be any element, including an input -->
					<button type="button" class="btn next"><i class="icon-arrow-right"></i></button>
					<button type="button" class="btn last"><i class="icon-step-forward"></i></button>
					<select class="pagesize input-mini" title="Select page size">
						<option selected="selected" value="10">10</option>
						<option value="20">20</option>
						<option value="30">30</option>
						<option value="40">40</option>
					</select>
					<select class="pagenum input-mini" title="Select page number"></select>
				</th>
			  </tr>';
		echo "</tfoot>\n";
		}
		//Table footer end
		
		echo "</table>\n";
		//Table end
	}
	
	//Runs after the widget is intialized
	public function run()
	{
		$this->registerClientScript();
		$this->genTable();
	}

}
?>